package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zcp
 * @version v1.0
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/chart")
public class ChartScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(ChartScriptController.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private ChartModel chartModel;

    /**
     * 处理客户漏斗、机会漏斗的阶段设置
     * 原配置是单独写ChartConfigEnum枚举，写死alias维护，不够灵活
     * 阶段推进器需求变动 2021年12月20日19:58:05 - 改为使用阶段类型维护（原设计是用code维护，但为了一次设置多个模板同时生效，改为类型，则就没必要再改她原有alias）
     *      为了不写脚本，继续使用原有的alias维护（虽然不应该，但是改为type要写脚本刷已有数据，影响较大，暂不大改动）
     * @param fixDataJobDTO
     * @param br
     * @return java.lang.String
     * @throws Exception
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    @RequestMapping(value = "/repairFunnelStage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String repairFunnelStage(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        long currentTime = DateTimeUtil.getInt();

        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (CollectionsUtil.isEmpty(corpidList)) {
            corpidList = companyModel.getCorpidList();
        }
        int totalCorp = corpidList.size();
        LOG.warn("开始处理漏斗阶段设置数据，一共{}家公司", totalCorp);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", 0);
        param.put("statisticsType", StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
        param.put("systemCodeIn", Arrays.asList(SystemCodeEnum.CUSTOMER_FUNNEL_CHART.getSystemCode(), SystemCodeEnum.OPPORTUNITY_FUNNEL_CHART.getSystemCode(), SystemCodeEnum.OPPORTUNITY_FUNNEL_HOME.getSystemCode()));
        // 每300家公司进行分页处理，计算分页页数
        int pageSize = 300;
        int pageNum = totalCorp % pageSize > 0 ? totalCorp / pageSize + 1 : totalCorp / pageSize;
        for (int currentPage = 1; currentPage <= pageNum; currentPage++) {
            int startIndex = (currentPage - 1) * pageSize;
            int endIndex = currentPage * pageSize;
            if (Objects.equals(currentPage, pageNum)) {
                endIndex = totalCorp;
            }
            List<String> subList = corpidList.subList(startIndex, endIndex);
            param.put("corpidIn", subList);
            LOG.warn("开始处理第{}——{}家公司的数据", startIndex, endIndex);
            List<ChartEntity> chartList = chartModel.findEntitys(param);
            List<ChartEntity> updateList = new ArrayList<>();
            for (ChartEntity chartEntity : chartList) {
                JSONArray buttonAttr = chartEntity.getButtonAttr();
                if (CollectionsUtil.isEmpty(buttonAttr)) {
                    //空的不用处理
                    continue;
                }
            }
            if (updateList.size() > BasicConstant.ZERO) {
                chartModel.updateBatchButtonAttr(updateList);
            }
        }
        LOG.warn("销售机会数据初始化完成，耗时{}", DateTimeUtil.getInt() - currentTime);
        return StringConstant.SUCCESS;
    }
}
